package br.com.sovi.resources.usuario;

import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openinsula.arena.tokenauth.Token;
import org.openinsula.arena.tokenauth.TokenAuthenticator;
import org.openinsula.vulcano.core.command.invoker.CommandInvoker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.com.sovi.persistence.Usuario;
import br.com.sovi.resources.Constants;

@Component
@Path("/usuario")
@Produces(Constants.MEDIA_TYPE_PRODUCES)
public class UsuarioResource {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private CommandInvoker commandInvoker;

	@Autowired
	private TokenAuthenticator tokenAuthenticator;

	@GET
	@Path("/allFromEmpresa")
	public List<UsuarioVO> getAll(@QueryParam("cnpjEmpresa") final String cnpj) throws JSONException {
		logger.debug("Procurando usuários de empresa por CNPJ: " + cnpj);

		List<Usuario> list = commandInvoker.invoke(new GetUsuarioByCnpjEmpresaCommand(cnpj));

		return UsuarioVO.convertList(list);
	}

	@POST
	@Path("/autenticacao")
	public Object autenticacao(@QueryParam("login") final String login, @QueryParam("senha") final String senha,
			final HttpServletResponse response) throws JSONException {
		logger.debug("Efetuando autenticacao de login: " + login);

		Boolean autenticado = commandInvoker.invoke(new EfetuaAutenticacaoCommand(login, senha));

		if (autenticado) {
			final Token token = new Token(login, System.currentTimeMillis());
			final String authenticate = tokenAuthenticator.authenticate(token);
			response.setHeader(TokenAuthenticator.TOKEN_AUTHENTICATOR_HEADER, authenticate);
		}

		JSONObject object = new JSONObject();

		return object.append("autenticado", autenticado);
	}

	public void setCommandInvoker(CommandInvoker commandInvoker) {
		this.commandInvoker = commandInvoker;
	}

	// @GET
	// @Path("/all")
	// @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	// public Object unique(@FormParam("empresa") final Long idContato) throws
	// JSONException {
	// logger.debug("opa");
	// return null;
	// }

}